<?php

/**
 * COOKIE类
 */
class Cookie {

    protected static $_instance = null;
    public $options = array('prefix' => 'pre_', 'tts' => 3600, 'domain' => '', 'salt' => '8jf6');

    function __construct() {
        if (Yaf_Registry::get("config")->cookie) {
            $this->options = array_merge($this->options, Yaf_Registry::get("config")->cookie->toArray());
        }
    }

    /**
     * 单例方法
     * @return Cookie
     */
    public static function getInstance() {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function __get($key) {
        return $this->get($key);
    }

    public function __set($key, $value) {
        return $this->set($key, $value);
    }

    /**
     * 获取COOKIE的值
     * @param string $name COOKIE的名称
     * @param string $data COOKIE的数据
     * @param int $time COOKIE有效时间 默认为配置中的时长,如果为0即关闭浏览器失效
     * @param string $path COOKIE有效的目录，默认为/
     * @return bool 成功返回true,失败返回false
     */
    public function set($name, $data, $time = null, $path = '/') {
        $time = is_null($time) ? intval($this->options['tts']) : intval($time);
        if ($name != '') {
            $mname = $this->options['prefix'] . $name;
            $mdata = $data != '' ? substr(md5($data . $this->options['salt']), 0, 16) : '';
            if ($data == '') {
                $time = time() - 86400;
            } else if ($time == 0) {
                $time = 0;
            } else {
                $time = time() + $time;
            }
            setcookie($name, $data, $time, $path, $this->options['domain']);
            setcookie($mname, $mdata, $time, $path, $this->options['domain']);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取COOKIE的值
     * @param string $name COOKIE的名称
     * @return string 如果未获取到则为空
     */
    public function get($name) {
        if (isset($_COOKIE[$name]) && isset($_COOKIE[$this->options['prefix'] . $name])) {
            return (substr(md5($_COOKIE[$name] . $this->options['salt']), 0, 16) != $_COOKIE[$this->options['prefix'] . $name]) ? '' : $_COOKIE[$name];
        } else {
            return '';
        }
    }

    /**
     * 清除COOKIE
     * @param string $name COOKIE的名称
     * @return bool 成功为true，失败为false
     */
    public function delete($name, $path = '/') {
        if ($name != '') {
            $expire = time() - 360000;
            $this->set($name, '', $expire, $path, $this->options['domain']);
            return true;
        } else {
            return false;
        }
    }

    /*
     * 清除COOKIE
     * @param string $name COOKIE的名称
     * @return bool 成功为true，失败为false
     */

    public function del($name, $path = '/') {
        return $this->delete($name, $path);
    }

}
